<?php

declare(strict_types=1);

namespace App\Activity\Job;

use App\Activity\Model\ActivityGoodsModel;
use App\Activity\Model\ActivityModel;
use App\Activity\Model\SecKillActivityRemindModel;
use App\Common\Service\MiniAppService;
use App\User\Model\MemberModel;
use Hyperf\AsyncQueue\Job;

class SubscribeJob extends Job
{
    public $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 2;

    public function __construct($id)
    {
        $this->params = $id;
    }

    public function handle()
    {
        $this->sendSpikeReminder($this->params);
    }

    /**
     * 发送开抢提醒
     * @param $id
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendSpikeReminder($id)
    {
        if (!$remind = SecKillActivityRemindModel::query()->find($id)) {
            return false;
        }
        if (!$open_id = MemberModel::query()->where('mid', $remind['mid'])->value('openid')) {
            return false;
        }
        try {
            [$template_id, $page, $data] = $this->getTemplateParams($remind);
            $result = (new MiniAppService)->sendSubscriptionMessage($open_id, $template_id, $page, $data);
            if ($result['code']) {
                throw new \Exception($result['msg'], $result['code']);
            }
        } catch (\Exception $e) {
            $result = $e;
        }
        $remind['is_success_send'] = 1;
        $remind['after_msg'] = var_export($result, true);
        return $remind->save();
    }

    /**
     * 获取指定提醒模板参数
     * @param $remind
     * @return array
     * @throws \Exception
     */
    public function getTemplateParams($remind)
    {
        if ($remind->is_closest == 1) {
            $activity = ActivityModel::query()->find($remind->activity_id);
            if (!$activity) {
                throw new \Exception('不存在的活动');
            }
            $template_id = MiniAppService::SPIKE_CLOSEST_ACTIVITY_BEGIN;
            $page = 'pages/seconds-kill/seconds-kill';
            $data = [
                'thing6' => [
                    'value' => '活动火爆进行中，登录小程序查看。',
                ],
                'time3'  => [
                    'value' => $activity->begin_date,
                ],
                'thing7' => [
                    'value' => mb_convert_encoding(substr_replace($activity->title, '...', 17), 'UTF-8'),
                ],
                'thing2' => mb_convert_encoding(substr_replace($activity->title, '...', 17), 'UTF-8'),
            ];
        } else {
            $activity_goods = ActivityGoodsModel::query()->find($remind['activity_goods_id'], [
                'goods_title',
                'activityID',
            ]);
            if (!$activity_goods) {
                throw new \Exception('不存在的活动商品');
            }
            $template_id = MiniAppService::SPIKE_ACTIVITY_GOODS_BEGIN;
            $page = 'pages/kill-details/kill-details?activitygoodsid=' . $remind['activity_goods_id'];
            $data = [
                'thing6' => [
                    'value' => '活动火爆进行中，登录小程序查看。',
                ],
                'date4'  => [
                    'value' => $activity_goods->activity->begin_date,
                ],
                'thing7' => [
                    'value' => mb_convert_encoding(substr_replace($activity_goods->activity->title, '...', 17), 'UTF-8'),
                ],
                'thing8' => [
                    'value' => mb_convert_encoding(substr_replace($activity_goods['goods_title'], '...', 17), 'UTF-8'),
                ],
            ];
        }
        return array_values(compact('template_id', 'page', 'data'));
    }
}
